package cn.org.intelli.lims.o2oa.model;

import cn.org.intelli.lims.o2oa.repository.PcaseRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.SQLDelete;
import org.springframework.stereotype.Service;
import xyz.erupt.annotation.Erupt;
import xyz.erupt.annotation.EruptField;
import xyz.erupt.annotation.fun.DataProxy;
import xyz.erupt.annotation.sub_erupt.Filter;
import xyz.erupt.annotation.sub_field.Edit;
import xyz.erupt.annotation.sub_field.EditType;
import xyz.erupt.annotation.sub_field.View;
import xyz.erupt.annotation.sub_field.ViewType;
import xyz.erupt.annotation.sub_field.sub_edit.ReferenceTableType;
import xyz.erupt.annotation.sub_field.sub_edit.Search;

import javax.annotation.Resource;
import javax.persistence.*;
import java.util.Date;
import java.util.UUID;

@Service
@Getter
@Setter
@Entity
@Table(name = "lims_pcase_op")
@SQLDelete(sql = "update lims_pcase_op set deleted = true, delete_time = now() where id = ?")
@Erupt(name = "案件办理记录信息", dataProxy = PcaseOp.class, filter = @Filter("PcaseOp.deleted = false"))
public class PcaseOp implements DataProxy<PcaseOp> {
    @Id
    @EruptField(views = @View(title = "", type = ViewType.QR_CODE))
    private String id;
    @ManyToOne
    @EruptField(views = @View(title = "案件信息", column = "ajbh"), edit = @Edit(title = "案件信息", type = EditType.REFERENCE_TABLE, referenceTableType = @ReferenceTableType(id = "id", label = "ajbh"), search = @Search))
    private Pcase pcase;
    @EruptField(views = @View(title = "办理步骤"), edit = @Edit(title = "办理步骤", search = @Search(vague = true)))
    private String stage;
    @ManyToOne
    @EruptField(views = @View(title = "办理人员信息", column = "name"), edit = @Edit(title = "办理人员信息", type = EditType.REFERENCE_TABLE, referenceTableType = @ReferenceTableType(id = "id", label = "name"), search = @Search))
    private Person person;
    @Column(name = "op_time")
    @EruptField(views = @View(title = "办理时间"), edit = @Edit(title = "办理时间", search = @Search(vague = true)))
    private Date opTime;
    @Column(name = "delete_time")
    private Date deleteTime;
    private Boolean deleted = false;

    @Override
    public void beforeAdd(PcaseOp pcaseOp) {
        if (pcaseOp.getId() == null) {
            pcaseOp.setId(UUID.randomUUID().toString());
        }
    }

    @Transient
    @Resource
    private PcaseRepository pcaseRepository;

    @Override
    public void afterAdd(PcaseOp pcaseOp) {
        if (pcaseOp.getStage() == "") {
            pcaseRepository.findById(pcaseOp.getPcase().getId()).ifPresent(pcase -> pcase.setStatus("无状态"));
        }
    }
}
